/*
 * Canvas Game Library - gl
 * 
 * A module that adds gl functionality to the library!
 */

CGL.gl = {
	VERTEX_SHADER : 0,
	FRAGMENT_SHADER : 1,
	vShader : null,
	fShader : null,
	program : null,
	vertexLocation : null,
	texCoordLocation : null,
	colorLocaton : null,
	noTextureLocation : null,
	
	loadShader : function(xhr, type) {
		var shaderScript = xhr.responseText;
		var shader;
		
		shader = CGL.gl.compileShader(shaderScript, type);
		if(type == CGL.gl.VERTEX_SHADER) {
			CGL.gl.vShader = shader;
		} else if(type == CGL.gl.FRAGMENT_SHADER) {
			CGL.gl.fShader = shader;
		}
	},
	
	compileShader : function(shaderSource, type) {
		var gl = CGL.canvas.getContext();
		var shader;
		
		if(type == CGL.gl.VERTEX_SHADER) {
			shader = gl.createShader(gl.VERTEX_SHADER);
		} else if(type == CGL.gl.FRAGMENT_SHADER) {
			shader = gl.createShader(gl.FRAGMENT_SHADER);
		} else {
			CGL.util.printLn("No valid type specified!");
			return null;
		}
		
		gl.shaderSource(shader, shaderSource);
		gl.compileShader(shader);
		
		if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            CGL.util.printLn(gl.getShaderInfoLog(shader));
            return null;
        } else {
        	CGL.util.printLn("Shader compiled correctly!");
        	return shader;
        }
	},
	
	initShaders : function(vShader, fShader) {
		var gl = CGL.canvas.getContext();
		CGL.ajax.loadShader(fShader, CGL.gl.loadShader, 1);
		CGL.ajax.loadShader(vShader, CGL.gl.loadShader, 0);

		CGL.gl.program = gl.createProgram();  
		
		gl.attachShader(CGL.gl.program, CGL.gl.vShader);  
		gl.attachShader(CGL.gl.program, CGL.gl.fShader);  
		gl.linkProgram(CGL.gl.program);  

		// If creating the shader program failed, alert  

		if (!gl.getProgramParameter(CGL.gl.program, gl.LINK_STATUS)) {  
			CGL.util.printLn("Unable to initialize the shader program.");  
		} else {
			CGL.util.printLn("Shader program initilized without error!");
		}

		gl.useProgram(CGL.gl.program);
	},
	
	showFPS : function(font, x, y) {
		var fps, delta;
		delta = new Date();
		if(delta.getTime() - CGL.util.LASTUPDATE > 1000)
		{
			CGL.util.FPS = CGL.util.FRAMES;
			CGL.util.FRAMES = 0;
			CGL.util.LASTUPDATE = delta.getTime();
		}
		else
		{
			CGL.util.FRAMES++;
		}
		if(x == undefined || y == undefined)
		{
			font.drawString("FPS: " + CGL.util.FPS, 10, 10);
		}
		else
		{
			font.drawString("FPS: " + CGL.util.FPS, x, y);
		}
	}
};